import {globalValue} from "@/core/config/globalConfig";
import {request} from "@/core/AxiosConfig";
import store from "@/store";
import {userApi} from "@/core/request/api/UserApi";
import Vue from "vue";
import VueRouter from "vue-router";
import routeMsg from "@/router";
import {RoleApi} from "@/core/request/api/RoleApi";
const router=new VueRouter(routeMsg)
Vue.use(VueRouter)  //Vue全局使用Router
router.beforeEach((to, from, next) => {
    if (to.meta.title) document.title = globalValue.protectTitle()+to.meta.title
    else document.title = globalValue.protectTitle()
    if (to.path == '/login') {
        if (sessionStorage.getItem('loginStatus') == null){
            store.state.user.token=undefined
            next()
        }
        else next('/datapage')
    }
    else {
        if (to.meta.mustLogin == true) {
            if (sessionStorage.getItem('loginStatus') == null) {
                request
                    .get(userApi.getInfo)
                    .then((res) => {
                        if (res.data.data == null||res.data.code) {
                            console.log(res.data.message)
                            // router.push({path: '/login'})
                            sessionStorage.removeItem('loginStatus')
                            next(`/login?redirect=${to.path}`)
                        } else {
                            Vue.prototype.$loginStatus = res.data.data
                            sessionStorage.setItem(
                                'loginStatus',
                                JSON.stringify(res.data.data)
                            )
                            console.log(Vue.prototype.$loginStatus)
                                RoleApi.getRolesByTree().then(res=>{
                                    if (res.data&&!res.data.code){
                                        let list = res.data.data.nodes;
                                        let roles = store.state.user.roles = {};
                                        for (let i = 0; i < list.length; i++) {
                                            let item = list[i];
                                            roles[item.name]=item.label
                                        }
                                    }
                                })
                            next()
                        }
                    })
                    .catch(() => {
                        next(`/login?redirect=${to.path}`)
                    })
            } else {
                Vue.prototype.$loginStatus = JSON.parse(
                    sessionStorage.getItem('loginStatus')
                )
                next()
            }
        }
        else next()
    }
})
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router;